package org.example.controller;

import org.example.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    HttpServletRequest request;
    @Value("${waimai.path}")
    private String path;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        int i = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(i);
        UUID uuid = UUID.randomUUID();
        File file1 = new File(path);
        String fileName = uuid + substring;
        try {
            if (!file1.exists()) {
                file1.mkdir();
            }
            file.transferTo(new File(path + uuid + substring));
            ArrayList<String> strings = new ArrayList<>();
            strings.add(fileName);
            HttpSession session = request.getSession();
            session.setAttribute("path", path);
            session.setAttribute("imglist", strings);

        } catch (Exception e) {
            e.printStackTrace();

        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            File file = new File(path + name);
            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpg");
//            response.setContentType("application/json");
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = fileInputStream.read(b)) != -1) {
                outputStream.write(b);
                outputStream.flush();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
